package com.example.testapp.activity.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

/**
 * Created by l on 2016/8/4.
 */
public class CHImageView extends ImageView {

    /**
     * 用于记录默认下载中状态的图片
     */
    private int downLoadingImageId = 0;
    private int downLoadingImagefailureId = 0;
    // 图片是否加载成功
    private boolean loadSuccess = false;

    public CHImageView(Context context) {
        super(context);
        initView(context);
    }

    public CHImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public CHImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCacheSize(32 * 1024 * 1024)
                .memoryCacheSize(4 * 1024 * 1024)
                .build();
        ImageLoader.getInstance().init(config);
    }

    /**
     * 对外接口，用于调用ImageView的异步下载图片功�? *
     *
     * @param url
     *            图片的URL
     */
    public void loadImage(String url) {
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                 .showStubImage(downLoadingImageId)
                 .showImageForEmptyUri(downLoadingImagefailureId)
                 .cacheInMemory()
                 .cacheOnDisc()
                 .showImageOnFail(downLoadingImagefailureId)
                 .bitmapConfig(Bitmap.Config.RGB_565)
                 .build();
        ImageLoader.getInstance().displayImage(url, this, options);
    }

    public boolean isLoadSuccess() {
        return loadSuccess;
    }
}
